<template>
  <div class="authority">
    <div class="container">
      <div class="body">
        <a-menu v-model="current" mode="horizontal" style="margin-bottom:20px">
          <a-menu-item key="authority" @click="mod='authority'"> <a-icon type="copy" />权限规则</a-menu-item>
          <a-menu-item key="list" @click="mod='list'"> <a-icon type="unordered-list" />权限列表</a-menu-item>
        </a-menu>
        <div class="authorityDiv" v-if="mod==='authority'">
          <div class="action acea-row row-middle">
            <a-button type="primary" @click="showModal">
              <a-icon type="plus" />
              添加权限规则
            </a-button>
          </div>
          <a-table :columns="columns" class="table" :loading="rulesLoading" :pagination="false" rowKey="id" :data-source="rules" >
            <div slot="rules" slot-scope="record" :title="changeRules(record.rules)" style="width:400px;overflow: hidden;text-overflow:ellipsis; white-space: nowrap;">
              {{changeRules(record.rules)}}
            </div>
            <div slot="is_use" slot-scope="record">
              <a-switch :checked="record.is_use==1?true:false" checked-children="启用" un-checked-children="关闭"  @change="(checked)=>changeRulesUse(record.id,checked)" />
            </div>
            <div slot="action" class="act acea-row row-middle" slot-scope="record">
              <a href="javascript:;" class="acea-row row-middle" @click="showModal(record.id)">修改权限<p></p></a>
              <a-popconfirm title="确认删除" ok-text="确定" cancel-text="取消" @confirm="delRule(record.id)" >
                <a href="javascript:;" class="acea-row row-middle" >删除</a>
              </a-popconfirm>
            </div>
          </a-table>
        </div>
        <div class="authorityList" v-if="mod === 'list'">
          <div class="action acea-row row-middle">
            <a-button type="primary" @click="showModa02">
              <a-icon type="plus" />
              添加权限
            </a-button>
          </div>
          <a-table :columns="columns02" :loading="authorityLoading" class="table" :pagination="false" rowKey="id" :data-source="authorityTree" >
            <div slot="url" class="act acea-row row-middle" slot-scope="record">
              <span>{{record.type | changeType}} {{record.url}}</span>
            </div>
            <div class="acea-row row-middle" slot="is_use" slot-scope="record">
              <a-switch :checked="record.is_use==1?true:false" checked-children="启用" un-checked-children="关闭"  @change="(checked)=>changeUse(record.id,checked)" />
            </div>
            <div slot="action" class="act acea-row row-middle" slot-scope="record">
              <a href="javascript:;" class="acea-row row-middle" @click="showModa02(record.id)">编辑<p></p></a>
              <a-popconfirm title="确认删除" ok-text="确定" cancel-text="取消" @confirm="delAuthority(record.id)" >
                <a href="javascript:;" class="acea-row row-middle" >删除</a>
              </a-popconfirm>
            </div>
          </a-table>
        </div>
      </div>
    </div>
    <modal :title="formRulesMod==='add'?'添加规则权限':'编辑规则权限'" :show="show" @close="hideModal" width="600px">
      <a-form-model ref="formRules" :model="formRules" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="规则名称" prop="title" required>
          <a-input v-model="formRules.title" />
        </a-form-model-item>
        <a-form-model-item label="是否启用" prop="is_use" required>
          <a-switch :checked="formRules.is_use==1?true:false" checked-children="启用" un-checked-children="关闭" @change="(checked)=>formRules.is_use = checked?1:0" />
        </a-form-model-item>
        <a-form-model-item label="权限" prop="rules">
          <a-tree-select :tree-data="ruleData" treeCheckStrictly v-model="formRules.rules" :maxTagCount="2" tree-checkable :show-checked-strategy="SHOW_ALL" />
        </a-form-model-item>
        <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
          <a-button type="primary" @click="submitRules">提交</a-button>
        </a-form-model-item> 
      </a-form-model>
    </modal>
    <modal :title="formListMod==='add'?'添加子菜单':'编辑菜单'" :show="show02" @close="hideModal02" width="600px">
      <a-form-model ref="formList" :model="formList" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="规则名称" prop="title" required>
          <a-input v-model="formList.title" />
        </a-form-model-item>
        <a-form-model-item label="标识" prop="name" required>
          <a-input v-model="formList.name" />
        </a-form-model-item>
        <a-form-model-item label="请求方式" prop="type" >
          <a-select :value="formList.type?formList.type:null" @change="(val)=>formList.type = val" allowClear>
            <a-select-option :value="1">get</a-select-option>
            <a-select-option :value="2">post</a-select-option>
            <a-select-option :value="3">页面地址</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="请求地址" prop="url" allowClear>
          <a-input v-model="formList.url" />
        </a-form-model-item>
        <a-form-model-item label="父级栏目" prop="pid" required>
          <a-tree-select v-model="formList.pid" :tree-data="treeData" ></a-tree-select>
        </a-form-model-item>
        <a-form-model-item label="是否启用" prop="is_use">
          <a-switch :checked="formList.is_use==1?true:false" checked-children="启用" un-checked-children="关闭" @change="(checked)=>formList.is_use = checked?1:0" />
        </a-form-model-item> 
        <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
          <a-button type="primary" @click="submitList">提交</a-button>
        </a-form-model-item> 
      </a-form-model>
    </modal>
  </div>
</template>

<script>
import request from 'api/request'
import Modal from 'components/common/modal'
import {TreeSelect} from 'ant-design-vue'
const SHOW_ALL = TreeSelect.SHOW_ALL

const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id' },
  { title: '规则名', dataIndex: 'title', key: 'title'},
  { title: '权限', key: 'rules',width:'400' ,scopedSlots: { customRender: 'rules' }},
  { title: '是否启用', key: 'is_use' ,scopedSlots: { customRender: 'is_use' }},
  { title: '操作', key: 'action',width:'200' ,scopedSlots: { customRender: 'action' },fixed:'right'},
]

const columns02 = [
  { title: 'ID', dataIndex: 'id', key: 'id' },
  { title: '权限名', dataIndex: 'title', key: 'title'},
  { title: '标识', dataIndex: 'name', key: 'name'},
  { title: '接口', key: 'url',scopedSlots: { customRender: 'url' }},
  { title: '是否启用', key: 'is_use',scopedSlots: { customRender: 'is_use' }},
  { title: '操作', key: 'action',width:'200' ,scopedSlots: { customRender: 'action' }},
]

function changeTree(data){
  for(let i of data){
    i.key = i.value = i.id
    if(i.children){
      i.children = changeTree(i.children)
    }
  }
  return data;
}

export default {
  components:{
    Modal
  },
  data() {
    return {
      current:['authority'],
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      columns,
      columns02,
      SHOW_ALL,
      show:false,
      show02:false,
      rulesLoading:false,
      authorityLoading:false,
      treeData:[],
      ruleData:[],
      defaultFormRules:{
        id:'',
        title:'',
        is_use:1,
        rules:[]
      },
      formRules:{
        rules:[]
      },
      defaultFormList:{
        id:'',
        pid:'',
        title:'',
        name:'',
        type:'',
        url:'',
        is_use:1,
      },
      formList:{},
      formRulesMod:'add',
      formListMod:'add',
      authority_list:[],
      mod:'authority'
    }
  },
  created() {
    // this.getRules()
    this.getTreeData()
  },
  mounted() {
  },
  methods: {
    getRules(){
      const that = this
      this.rulesLoading = true
      this.$store.dispatch("admin/getRules").then(e=>{
        that.rulesLoading = false
      })
    },
    submitRules(){
      const that = this
      this.$refs.formRules.validate(vaild=>{
        if(vaild){
          let rules = ""
          console.log("submitRules",this.formRules)
          let formRules = JSON.parse(JSON.stringify(this.formRules))
          for(let i of formRules.rules){
            rules = rules + i.value + ','
          }
          rules = rules.substring(0,rules.length-1)
          console.log(rules)
          // formRules.rules = formRules.rules.toString()
          formRules.rules = rules
          if(this.formRulesMod === "add"){
            request.post("/system/rules/add",formRules).then(e=>{
              if(e.status == 200){
                that.$message.success("添加成功")
                that.getRules()
                that.hideModal()
              }else{
                that.$message.error(e.msg)
              }
            })
          }else{
            formRules.method = "edit"
            request.post("/system/rules/edit",formRules).then(e=>{
              if(e.status == 200){
                that.$message.success("修改成功")
                that.getRules()
                that.hideModal()
              }else{
                that.$message.error(e.msg)
              }
            })
          }
        }
      })
    },
    submitList(){
      const that = this
      this.$refs.formList.validate(vaild=>{
        if(vaild){
          let formList = JSON.parse(JSON.stringify(this.formList))
          formList.type = formList.type?formList.type:0
          this.authorityLoading = true
          if(this.formListMod === 'add'){
            request.post("/system/authority/add",formList).then(e=>{
              that.authorityLoading = false
              if(e.status == 200){
                that.$message.success("添加成功")
                that.$store.dispatch("admin/getAuthority").then(e=>{
                  that.getTreeData()
                })
                that.hideModal02()
              }else{
                that.$message.error(e.msg)
              }
              that.getTreeData()
            })
          }else{
            formList.method = "edit"
            request.post("/system/authority/edit",formList).then(e=>{
              that.authorityLoading = false
              if(e.status == 200){
                that.$message.success("修改成功")
                that.$store.dispatch("admin/getAuthority").then(e=>{
                  that.getTreeData()
                })
                that.hideModal02()
              }else{
                that.$message.error(e.msg)
              }
            })
          }
        }
      })
    },
    getTreeData(){
      let that = this
      if(this.authorityTree.length != 0){
        let authorityTree = JSON.parse(JSON.stringify(this.authorityTree))
        let arr = [{id:0,title:'顶级栏目',value:0}]
        this.treeData = arr.concat(changeTree(authorityTree))
        this.ruleData = changeTree(authorityTree) 
      }else{
        this.$store.dispatch("admin/getAuthority").then(()=>{
          that.getTreeData()
        })
      }
    },
    showModal(id){
      if(typeof id === "number"){
        let list = this.rules.find(e=>e.id==id)
        let rules = list.rules!=""?list.rules.split(","):[]
        let rulesArr = []
        for (let i of rules){
          rulesArr.push({value:i})
        }
        let formRules = {}
        formRules.id = list.id
        formRules.title = list.title
        formRules.rules = rulesArr
        formRules.is_use = list.is_use
        this.formRules = JSON.parse(JSON.stringify(formRules))
        this.formRulesMod = 'edit'
      }else{
        this.formRules = JSON.parse(JSON.stringify(this.defaultFormRules))
        this.formRulesMod = 'add'
      }
      this.show = true
    },
    showModa02(id){
      if(typeof id === "number"){
        let list = this.authorityList.find(e=>e.id==id)
        let formList = {}
        formList.id = list.id
        formList.pid = list.pid
        formList.title = list.title,
        formList.name = list.name,
        formList.type = list.type,
        formList.url = list.url,
        formList.is_use = list.is_use
        this.formList = JSON.parse(JSON.stringify(formList))
        this.formListMod = 'edit'
      }else{
        this.formList = JSON.parse(JSON.stringify(this.defaultFormList))
        this.formListMod = 'add'
      }
      this.show02 = true
    },
    delRule(id){
      const that = this
      request.post("/system/rules/del",{id}).then(e=>{
        if(e.status == 200){
          that.getRules()
          that.$message.success("删除成功")
        }else{
          that.$message.error(e.msg)
        }
      })
    },
    delAuthority(id){
      const that = this
      request.post("/system/authority/del",{id}).then(e=>{
        if(e.status == 200){
          that.$store.dispatch("admin/getAuthority")
          that.$message.success("删除成功")
        }else{
          that.$message.error(e.msg)
        }
      })
    },
    changeRulesUse(id,checked){
      const that = this
      let params = {
        id,
        method:"changeUse",
        is_use:checked?1:0
      }
      request.post("/system/rules/edit",params).then(e=>{
        if(e.status == 200){
          that.getRules()
          that.$message.success("修改成功")
        }else{
          that.$message.error(e.msg)
        }
      })
    },
    changeUse(id,checked){
      const that = this
      this.authorityLoading = true
      let params = {
        id,
        method:"changeUse",
        is_use:checked?1:0
      }
      request.post("/system/authority/edit",params).then(e=>{
        if(e.status == 200){
          that.$store.dispatch("admin/getAuthority")
          that.$message.success("修改成功")
          this.authorityLoading = false
        }else{
          that.$message.error(e.msg)
        }
      })
    },
    changeRules(e){
      let arr = e.split(",")
      let text = ""
      for(let i of arr){
        let f = this.authorityList.find(e=>e.id == i)
        if(f){
          text = text + f.title + ","
        }
      }
      text = text.substring(0,text.length-1)
      return text;
    },
    hideModal(){
      this.show = false
      this.$refs.formRules.resetFields()
    },
    hideModal02(){
      this.show02 = false
      this.$refs.formList.resetFields()
    },
  },
  filters:{
    changeType(e){
      switch(e){
        case 1:
          return '[get]'
        break;
        case 2:
          return '[post]'
        break;
        case 3:
          return '[path]'
        break;
      }
    },
  },
  computed: {
    authorityTree(){
      return this.$store.state.admin.authorityTree
    },
    authorityList(){
      return this.$store.state.admin.authorityList
    },
    rules(){
      return this.$store.state.admin.rules
    }
  },
}
</script>

<style scoped>
  .authority .container{
    width: calc(100% - 32px);
    margin: 16px auto;
    background-color: #ffffff;
  }
  .authority .container .body{
    padding: 16px;
  }
  .authority .container .body .action{
    margin-bottom: 20px;
  }
  .authority .container .table .act p {
    height: 14px;
    width: 1px;
    margin: 0 10px;
    background-color: #515a6e;
  }
</style>